package cn.autumnorange.app.money.provider.service;

import cn.autumnorange.app.common.dto.ResultDto;
import cn.autumnorange.app.money.api.MoneyService2;
import cn.autumnorange.app.money.api.dto.MoneyDto;
import cn.autumnorange.app.money.provider.entity.MoneyEntity;
import cn.autumnorange.app.money.provider.repository.MoneyJpaRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Primary
@Service
@Slf4j
public class MoneyService2Impl implements MoneyService2 {
  @Autowired MoneyJpaRepository moneyJpaRepository;
  private int i = 0;
  // 加钱
  @Transactional
  @Override
  public ResponseEntity<ResultDto<MoneyDto>> add2(Long version, Long money) {
    //    Optional<MoneyEntity> moneyEntityOptional = moneyJpaRepository.findTeacherForUpdate(1L);
    Optional<MoneyEntity> moneyEntityOptional = moneyJpaRepository.findById(1L);

    if (moneyEntityOptional.isPresent()) {
      MoneyEntity moneyEntity = moneyEntityOptional.get();
      log.info("add2读到Money,version:" + moneyEntity.getMoney() + "  " + moneyEntity.getVersion());
//      if (version != moneyEntity.getVersion()) {
//        throw new RuntimeException("版本锁不一致");
//      }
      moneyEntity.setMoney(moneyEntity.getMoney() + money);
      moneyJpaRepository.save(moneyEntity);
    }
    i++;

    //    if (i % 2 == 0) {
    //      throw new RuntimeException("并发测试");
    //    }
    MoneyDto moneyDto = new MoneyDto();
    BeanUtils.copyProperties(money, moneyDto);
    return ResponseEntity.ok(ResultDto.createDataResult(moneyDto));
  }

  @Transactional
  @Override
  public ResponseEntity<ResultDto<Long>> getVersion(Long id) {
    Optional<MoneyEntity> moneyEntityOptional = moneyJpaRepository.findById(1L);

    if (moneyEntityOptional.isPresent()) {
      MoneyEntity moneyEntity = moneyEntityOptional.get();
      return ResponseEntity.ok(ResultDto.createDataResult(moneyEntity.getVersion()));
    }
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
        .body(
            ResultDto.createResult(
                HttpStatus.INTERNAL_SERVER_ERROR.value(), null, null, null, null, null));
  }
}
